// create Agora client
let swClient = null;

var localTracks = {
    videoTrack: null,
    audioTrack: null
  };
var remoteUsers = {};
var remoteUsersList = []; // add this line
// Agora client options
let options = {};

async function RTCjoin() {
  swClient = AgoraRTC.createClient({ mode: "rtc", codec: "h264" })
   // 获取数据
  let config = strToJson(sessionStorage.getItem('cTencentConfig'));
  console.log('config',config)
    let {appId, room, sig, userId} = config
    options = {
      channel: room,
      uid: userId,
      token: sig,
      appid: appId
    };

    // add event listener to play remote tracks when remote user publishes.
    swClient.on("user-published", handleUserPublished);
    swClient.on("user-unpublished", handleUserUnpublished);
    swClient.on("user-left", handleUserLeft);

    try {
      // join a channel and create local tracks, we can use Promise.all to run them concurrently
      [ options.uid, localTracks.audioTrack, localTracks.videoTrack ] = await Promise.all([
        // join the channel
        swClient.join(options.appid, options.channel, options.token || null, options.uid),
        // create local tracks, using microphone and camera
        AgoraRTC.createMicrophoneAudioTrack(),
        AgoraRTC.createCameraVideoTrack()
      ]);

      // play local video track
      localTracks.videoTrack.play("videoDiv2");

      // publish local tracks to channel
      await swClient.publish(Object.values(localTracks));
      console.log("本地视频发布成功");
    } catch (error) {
      console.error("加入房间或发布视频失败:", error);
    }
}

  async function subscribe(user, mediaType) {
    const uid = user.uid;
    try {
      // subscribe to a remote user
      await swClient.subscribe(user, mediaType);
      console.log("订阅远程用户成功:", uid, mediaType);

      if (mediaType === 'video') {
        const player = $(`
          <div id="player-wrapper-${uid}" class="remote-player-wrapper" style="height: 140px">
            <div id="player-${uid}" style="width: 100%; height: 100%;"></div>
          </div>
        `);
        $("#videoDiv1").append(player);
        user.videoTrack.play(`player-${uid}`);
      }
      if (mediaType === 'audio') {
        user.audioTrack.play();
      }
    } catch (error) {
      console.error("订阅远程用户失败:", error);
    }
  }

  function handleUserPublished(user, mediaType) {
    const id = user.uid;
    remoteUsers[id] = user;
    console.log('远程用户加入房间:', user, '媒体类型:', mediaType);
    subscribe(user, mediaType);
  }

  function handleUserUnpublished(user) {
    const id = user.uid;
    delete remoteUsers[id];
    $(`#player-wrapper-${id}`).remove();
    console.log('远程用户取消发布:', id);
  }

  function handleUserLeft(user) {
    const id = user.uid;
    delete remoteUsers[id];
    $(`#player-wrapper-${id}`).remove();
    console.log('远程用户离开:', id);
  }

  async function swleave() {
    console.log('退出房间')
    for (trackName in localTracks) {
      var track = localTracks[trackName];
      if(track) {
        track.stop();
        track.close();
        localTracks[trackName] = undefined;
      }
    }

    // remove remote users and player views
    remoteUsers = {};
    $("#remoteVideos").empty();

    // leave the channel
    await swClient.leave();
    console.log("离开房间成功");
  }
